<?php

class LoginForm extends CFormModel {
	public $username;
	public $password;
	private $_identity;

	public function rules() {
		return array(
			array('username, password', 'required'),
		);
	}

	public function attributeLabels() {
		return array(
			'username' => 'Tên đăng nhập',
			'password' => 'Mật khẩu',
		);
	}

	public function authenticate() {
		if( !$this->hasErrors()) {
			$this->_identity = new UserIdentity($this->username, User::model()->hashPassword($this->password));
			if($this->_identity->authenticate() != UserIdentity::ERROR_NONE) {
				$this->addError('password', 'Incorrect username or password.');
			}
		}
	}

	public function login() {
		if($this->_identity === null) {
			$this->_identity = new UserIdentity($this->username, User::model()->hashPassword($this->password));
			$this->_identity->authenticate();
		}
		if($this->_identity->errorCode === UserIdentity::ERROR_NONE) {
			$duration = 3600 * 24 * 30; // 30 days
			Yii::app()->user->login($this->_identity, $duration);
			return true;
		} else if($this->_identity->errorCode == - 1) {
			$this->addError('password', 'Tài khoản chưa kích hoạt.');
			return false;
		} else {
			$this->addError('password', 'Sai tài khoản hoặc mật khẩu.');
			return false;
		}

	}
}
